#!/usr/bin/env node

const request = require('superagent');
const shell = require('shelljs');
const _ = require('lodash');
const utils = require('./js/utils');
const program = require('./js/dialog').commander();
const logFile = require('path').join(require('os').homedir(), '.xn_history', '.xn_xget_history');

program
.version('0.0.1')
.option('-u, --url [http://127.0.0.1:3000/test]', 'url of api')
.option('-d, --data <json>', 'data must be json format', (v)=>eval('v='+v), {})
.option('-l, --log [n]', 'show log n items, default: 10')
.parse(process.argv);

const { url, log, data } = program;
if (log) {
    console.log(shell.tail({'-n': log === true ? 10 : log}, logFile).toString());
    process.exit(0);
}
request.get(url)
.query(data)
.end((error, res) => {
    if (error) {
        console.error('recv error:', error);
    } else {
        if (res.text) {
            console.log(res.text);
        } else if (_.size(res.body)) {
            console.log(res.body);
        } else {
            console.log(res.res.headers);
        }
    }
    utils.saveHistory(logFile, `xget -u ${url} -d "${utils.stringify(data, 2)}"`);
});
